package com.songtech.server.task;

import com.songtech.server.Jedis.JedisBaseDao;
import com.songtech.server.utils.GetKeysUtils;

import java.io.Serializable;

/**
 * Create By YINN on 2018/4/20 18:29
 * Description :
 */

public class RedisLock<T extends Serializable> {


//    private String lockKey;

    private String key;

    private T obj;

    private static JedisBaseDao<Serializable> jedisBaseDao;

    private static final long LIVE_TIME = 3600;

    public RedisLock(String lockKey, String key, T obj, JedisBaseDao<Serializable> jedisBaseDao) {
        this.key = GetKeysUtils.combineAnyKeys(lockKey, key);
        this.obj = obj;
        this.jedisBaseDao = jedisBaseDao;
    }

    public static Object getLockedEntry(String lockKey,String key) {

        return  jedisBaseDao.get(GetKeysUtils.combineAnyKeys(lockKey, key));

    }

    public boolean lock() {

        return jedisBaseDao.put(key, obj, LIVE_TIME);

    }


    public boolean isLock() {

        if (getObj() != null) {

            return false;

        }

        return true;
    }

    public static void removeLock(String lockKey, String key) {

        System.out.println("移除对象锁,锁id:"+GetKeysUtils.combineAnyKeys(lockKey, key));

        jedisBaseDao.delete(GetKeysUtils.combineAnyKeys(lockKey, key));

    }

    public void removeLock() {

        jedisBaseDao.delete(key);

    }


    public T getObj() {
        return obj;
    }

    public String getKey() {
        return key;
    }
}
